<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>defineProperty</title>
</head>

<body>
    <script>
        // defineProperty 给对象添加具有get 和 set方法的属性
        let obj = Object.defineProperty({}, "name", {
            configurable: true,
            enumerable: true,
            get() {
                console.log('get');
                return "张三";
            },
            set(newValue) {
                console.log('修改的值：', newValue);
            }
        })

        console.log(obj)

        for (let k in obj) {
            console.log(k);
        }

        obj.name;
        obj.name = '李四';
        delete obj.name;


        // 对象的每个属性添加set和get方法
        let obj = {
            name: '张三',
            age: 20
        };

        for (let key in obj) {
            let value = obj[key];
            Object.defineProperty(obj, key, {
                configurable: true,
                enumerable: true,
                get() {
                    console.log(`${key} get`);
                    return value
                },
                set(newValue) {
                    console.log(`${key} set`);
                    value = newValue;
                }
            })
        }
        obj.name;
        obj.name = '李四';
        obj.age;
        obj.age = '30';
    </script>
</body>

</html>